/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-04-15 14:29:31
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2024-12-25 11:06:52
 * @FilePath: \Backstage\Server\src\router\blog\article.js
 */
const createSql = require('../../utils/sql');
const express = require('express');
const db = require('../../utils/connDB');
const router = express.Router();
const Excel = require('exceljs');
const { verifyToken } = require('../../utils/handleToken');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { handleError } = require('../../utils/common.js');

// 获取文章列表
router.get('/list', async (req, res) => {
  let { page, size, title, type, game, label, isUnPage = true } = req.query;
  let offset = (page - 1) * size;

  let sql = `SELECT id, title, subTitle, cover, createTime, updateTime, type, game, labels, isPreview, readCount, shareCount, (SELECT COUNT(*) FROM comment WHERE type = 1 AND isCheck = 1 AND articleId = article.id) as commentCount FROM article WHERE 1=1 ${
    title ? `AND title LIKE '%${title}%'` : ''
  } ${game ? `AND game = '${game}'` : ''} ${type ? `AND type = '${type}'` : ''} ${label ? `AND labels LIKE '%${label}%'` : ''} and delFlag = 0 ${
    !isUnPage || isUnPage == 'false' ? `ORDER BY id DESC` : `ORDER BY id DESC LIMIT ${size} OFFSET ${offset}`
  }`;
  let lensql = `SELECT count('id') as total FROM article WHERE 1=1 ${title ? `AND title LIKE '%${title}%'` : ''} ${game ? `AND game = '${game}'` : ''} ${
    type ? `AND type = '${type}'` : ''
  } ${label ? `AND labels LIKE '%${label}%'` : ''} and delFlag = 0`;

  const params = [0];
  try {
    db.queryAsync(lensql, []).then(lenRes => {
      const total = lenRes.results[0]['total'];
      db.queryAsync(sql, params).then(ress => {
        let result = ress.results;
        res.send({
          code: 200,
          data: result,
          total: total,
          msg: '获取成功'
        });
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 获取文章详情
router.get('/detail/:id', async (req, res) => {
  const { id } = req.params;
  const sql = `SELECT * FROM article WHERE id = ${id}`;

  let commentCountSql = `select* from comment where 1=1 and isCheck = 1 and type = 1 and articleId =${id}`;
  try {
    db.queryAsync(sql, []).then(ress => {
      let result = ress.results[0];
      db.queryAsync(commentCountSql, []).then(commentCountRes => {
        result.commentCount = commentCountRes.results.length;
        res.send({
          code: 200,
          data: {
            ...result
          },
          msg: '获取成功'
        });
      });
      db.queryAsync(`UPDATE article SET readCount = readCount + 1 WHERE id = ${id}`, []);
    });
  } catch (error) {
    res.send({
      code: 200,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 更新评论次数
router.put('/commentCount', async (req, res) => {
  const { id } = req.body;
  const sql = `UPDATE article SET commentCount = commentCount + 1 WHERE id = ${id}`;
  try {
    db.queryAsync(sql, []).then(ress => {
      res.send({
        code: 200,
        data: null,
        msg: '更新成功'
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 获取访问量  TOP的文章
router.get('/topRead', async (req, res) => {
  const { size = 3 } = req.query;
  const sql = `SELECT id, title, cover, readCount, createTime FROM article WHERE delFlag = 0 ORDER BY readCount DESC LIMIT ${size}`;
  try {
    db.queryAsync(sql, []).then(ress => {
      res.send({
        code: 200,
        data: ress.results,
        msg: '获取成功'
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 更新分享次数
router.put('/shareCount', async (req, res) => {
  const { id } = req.body;
  const sql = `UPDATE article SET shareCount = shareCount + 1 WHERE id = ${id}`;
  const shareCountSql = `SELECT shareCount FROM article WHERE id = ${id}`;
  try {
    db.queryAsync(sql, []).then(ress => {
      db.queryAsync(shareCountSql, []).then(shareCountRes => {
        res.send({
          code: 200,
          data: shareCountRes.results[0].shareCount,
          msg: '更新成功'
        });
      });
    });
  } catch (error) {
    res.send({
      code: 200,
      data: null,
      msg: '500 error=' + error
    });
  }
});

// 新增文章
router.post('/add', async (req, res) => {
  const token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    let { title, subTitle, cover, content, type, isPreview, labels, game = 0 } = req.body;
    let sql = createSql
      .insert('article')
      .set({
        title,
        subTitle,
        cover,
        content: encodeURIComponent(content),
        type,
        createTime: new Date(),
        status: 1,
        delFlag: 0,
        isPreview,
        labels,
        game
      })
      .end();
    const params = [new Date(), 1, 0];
    db.queryAsync(sql, params).then(ress => {
      res
        .send({
          code: 200,
          data: null,
          msg: '新增成功'
        })
        .catch(err => {
          handleError(res, err);
        });
    });
  } catch (error) {
    handleError(res, error);
  }
});

// 修改文章
router.put('/edit', async (req, res) => {
  const token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    let { id, title, subTitle, cover, content, type, isPreview, labels, game } = req.body;
    let data = {
      title,
      subTitle,
      cover,
      content: encodeURIComponent(content),
      type,
      isPreview,
      labels,
      game,
      updateTime: new Date()
    };

    const sql = createSql
      .update('article')
      .set(data)
      .where('id=' + id)
      .build();
    const params = [new Date()];

    db.queryAsync(sql, [params]).then(ress => {
      res.send({
        code: 200,
        data: null,
        msg: '修改成功'
      });
    });
  } catch (error) {
    handleError(res, error);
  }
});

// 删除文章
router.delete('/del/:id', async (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    const { id } = req.params;
    const sql = `UPDATE article SET delFlag = 1 WHERE id = ${id}`;
    const params = [1];
    db.queryAsync(sql, [params]).then(ress => {
      res.send({
        code: 200,
        data: null,
        msg: '删除成功'
      });
    });
  } catch (error) {
    handleError(res, error);
  }
});

// 预览 文章 html
router.get('/preview/:id', async (req, res) => {
  const { id } = req.params;
  const sql = `SELECT content FROM article WHERE id = ${id}`;
  try {
    db.queryAsync(sql, []).then(ress => {
      let content = ress.results[0].content;
      content = decodeURIComponent(content);
      let reg = /<!DOCTYPE html>.*<\/html>/s;
      let reg2 = /<html>.*<\/html>/s;
      content = content.replace(/&#39;/g, "'");
      content = content.replace(/&gt;/g, '>');
      content = content.replace(/&lt;/g, '<');
      content = content.replace(/&#39;/g, "'");

      let htmlstr = content.match(reg) ? content.match(reg)[0] : '';
      if (!htmlstr) htmlstr = content.match(reg) ? content.match(reg2)[0] : '';
      if (!htmlstr)
        htmlstr = `
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>Document</title>
        </head>
        <body style="display: flex; justify-content: center; align-items: center; height: 100vh">
          <p>内容阅览出错咯， 请联系博主</p>
        </body>
      </html>
      `;

      let pathstr = path.resolve(__dirname, '../../../public/html/preview.html');
      fs.readFile(pathstr, 'utf8', (err, data) => {
        if (err) {
          // return res.send({
          //   code: 500,
          //   data: null,
          //   msg: '500 error readFile =' + err
          // });
          fs.mkdirSync(path.resolve(__dirname, '../../../public/html'), { recursive: true });
        }
        fs.writeFile(pathstr, htmlstr, 'utf8', err => {
          if (err) {
            return res.send({
              code: 500,
              data: null,
              msg: '500 error writeFile =' + err
            });
          }
          const url = 'http://124.223.41.220:3333/html/preview.html';
          res.send({
            code: 200,
            data: url,
            msg: '预览成功'
          });
        });
      });
    });
  } catch (error) {
    res.send({
      code: 500,
      data: null,
      msg: '500 try catch =' + error
    });
  }
});

module.exports = router;
